package com.lucy.management.config.auth;

import com.alibaba.fastjson.JSON;
import com.lucy.management.domain.SysUser;
import com.lucy.management.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


/**
 *
 *
 * @ClassName: AdminInterceptor
 * @Description:拦截器
 * @author:
 * @date:
 */
public class AdminInterceptor implements HandlerInterceptor {

   /* @Autowired
    private SysUserService sysUserService;

    @Autowired
    BaseStudentService baseStudentService;*/

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        /*String token = request.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //PassToken，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        // 执行认证
        if (StringUtils.isEmpty(token)) {
            getWriter(response,"无token，请重新登录");
            return false;
        }

        // 获取 token 中的 userId
        // 验证 token
        String userId=null;
        try {
            userId = (String)JwtUtil.parseJWT(token).get("userId");
        }catch (io.jsonwebtoken.ExpiredJwtException e){
            getWriter(response,"登录超时，请重新登录");
            return  false;
        } catch (Exception j) {
            getWriter(response,"token错误，请重新登录");
            return  false;
        }
        //获取用户类别
        String role =(String) JwtUtil.parseJWT(token).get("role");
        //验证用户权限
        if("admin".equals(role)){
            SysUser user = sysUserService.findById(userId);
            if (user == null) {
                getWriter(response,"用户不存在，请重新登录");
                return false;
            }

        }
        else if("student".equals(role)){
            BaseStudent baseStudent = baseStudentService.findById(userId);
            if (baseStudent == null) {
                getWriter(response,"用户不存在，请重新登录");
                return false;
            }
        }*/

        return true;
    }

    private void getWriter(HttpServletResponse response, String msg) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = getPrintWriter(response);
        Map<String, String> map = new HashMap<>();
        map.put("code", "401");
        map.put("flag", "false");
        map.put("msg", msg);
        writer.write(JSON.toJSONString(map));
    }

    private PrintWriter getPrintWriter(HttpServletResponse response) throws IOException {
        return response.getWriter();
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
//         System.out.println("执行了TestInterceptor的postHandle方法");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        System.out.println("执行了TestInterceptor的afterCompletion方法");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With, token");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT, DELETE");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
    }

}